package com.zm.study.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.WebStatFilter;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据源设置
 * @author
 *
 */
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = SlaveDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "slaveSqlSessionFactory", sqlSessionTemplateRef = "slaveSqlSessionTemplate")
@AutoConfigureAfter({SlaveDataSourceConfig.class})
public class SlaveDataSourceConfig {
	
	@Autowired
	private PageHelper pageHelper;
	
	protected static final String PACKAGE = "com.zm.study.slave";
	protected static final String MAPPER_LOCATION = "classpath*:mybatis/*/*/*.xml";
	
	@Value("${spring.druid.slave.datasource.url}")
    private String url;

    @Value("${spring.druid.slave.datasource.username}")
    private String user;

    @Value("${spring.druid.slave.datasource.password}")
    private String password;

    @Value("${spring.druid.slave.datasource.driverClassName}")
    private String driverClass;
    
    @Value("${spring.druid.maxActive}")
    private int maxActive;
    
    @Value("${spring.druid.minIdle}")
    private int minIdel;
    
    @Value("${spring.druid.maxWait}")
    private long maxWait;

    @Bean(name = "slaveDataSource")
    public DataSource slaveDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        dataSource.setMaxActive(maxActive);
        dataSource.setMinIdle(minIdel);
        dataSource.setMaxWait(maxWait);
        try {
            dataSource.setFilters("stat,wall,logback");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        Properties properties = new Properties();
        properties.put("druid.stat.mergeSql","true");
        properties.put("druid.stat.slowSqlMillis","5000");
        dataSource.setConnectProperties(properties);
        dataSource.setUseGlobalDataSourceStat(true);
        return dataSource;
    }


    /**
     * 注册一个：filterRegistrationBean
     * @return
     */

    @Bean
    public FilterRegistrationBean druidStatFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        //添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");
        //添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    
    @Bean(name = "slaveTransactionManager")
    public DataSourceTransactionManager slaveTransactionManager(){
        return new DataSourceTransactionManager(slaveDataSource());
    }
    @Bean(name = "slaveSqlSessionFactory")
     public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource") DataSource slaveDataSource)
            throws Exception {
    	 final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    	 /**添加分页插件*/
         sessionFactory.setPlugins(new Interceptor[]{pageHelper});
         sessionFactory.setDataSource(slaveDataSource);
         sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(SlaveDataSourceConfig.MAPPER_LOCATION));
         ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
         sessionFactory.setConfigLocation(resolver.getResource("classpath:mybatis/mybatis-config.xml"));
         return sessionFactory.getObject();
    }
    @Bean(name = "slaveSqlSessionTemplate")
    public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory slaveSqlSessionFactory) {
        return new SqlSessionTemplate(slaveSqlSessionFactory);
    }
}